namespace TomatoBreak.Infrastructure
{
    using System;
    using System.Web;

    using DataAccess;
    using DomainObjects;

    public class CurrentUserProvider : ICurrentUserProvider
    {
        private static readonly object contextKey = new object();

        private readonly IRepository<User> repository;
        private readonly Func<HttpContextBase> lazyHttpContext;

        public CurrentUserProvider(IRepository<User> repository, Func<HttpContextBase> lazyHttpContext)
        {
            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }

            if (lazyHttpContext == null)
            {
                throw new ArgumentNullException("lazyHttpContext");
            }

            this.repository = repository;
            this.lazyHttpContext = lazyHttpContext;
        }

        public User CurrentUser
        {
            get { return GetUser(); }
        }

        private User GetUser()
        {
            var httpContext = lazyHttpContext();
            var user = httpContext.Items[contextKey] as User;

            if ((user == null) && httpContext.User.Identity.IsAuthenticated)
            {
                var tempUser = repository.FindOne(u => u.UserName == httpContext.User.Identity.Name);

                if ((tempUser != null) && !tempUser.Locked)
                {
                    httpContext.Items[contextKey] = user = tempUser;
                }
            }

            return user;
        }
    }
}